import {getUserTempId} from "@/utils/userabout";
import {reqCode, reqUserRegister, reqUserLogin, reqUserInfo, reqUserLogout} from "@/api";

const state = {
    userTempId: getUserTempId(),
    code: '',
    token: localStorage.getItem('token_key'),
    userInfo:{}
}
const mutations = {
    SET_CODE(state, code) {
        state.code = code
    },
    SET_TOKEN(state, token){
        state.token = token
    },
    SET_USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    REMOVE_TOKEN_USERINFO(state) {
        state.token =''
        state.userInfo = {}
    }
}
const actions = {
    //获取验证码
    async getCode({commit},phone) {
        const result = await reqCode(phone)
        if (result.code === 200){
            commit('SET_CODE',result.data)
            return result.data
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
    //注册用户
    // eslint-disable-next-line no-unused-vars
    async getUserRegister({commit},userInfo){
        const result=await reqUserRegister(userInfo)
        if (result.code === 200){
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
    //用户登录，获取token并保存
    async getUserLogin({commit},userInfo){
        const result=await reqUserLogin(userInfo)
        if (result.code === 200) {
            commit('SET_TOKEN',result.data.token)
            localStorage.setItem('token_key',result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    //获取用户信息
    async getUserInfo({commit}){
        const result = await reqUserInfo()
        if (result.code === 200) {
            commit('SET_USERINFO',result.data)
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
    //清楚token和userInfo
    getRemoveTokenAndUserInfo({commit}){
        localStorage.removeItem('token_key')
        commit('REMOVE_TOKEN_USERINFO')

    },
    //退出登陆
    async getUserLogout({commit,dispatch}){
        const result=await reqUserLogout()
        if (result.code === 200){
            dispatch('getRemoveTokenAndUserInfo')
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    }

}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}
